using UnityEngine;
using System.Collections;

/**
 * Script of script enabling behaviour description.
 * The purpose of this class is to enable scripts for control triggering.
 * @author Benjamin Bruneau
 */
public class EnablerScript : MonoBehaviour 
{
	
	private const string REPLAY_MODE_NAME = "ReplayMode"; // Replay Mode GameObject's name
	private const string BALL_NAME = "Ball"; // Main GameObject's name
	
	private GameObject _replayMode; // Replay Mode GameObject
	
	public GameObject _dataContainer; // Data container GameObjec
	public GameObject _lastLevel; //Last stage
	
	/**
	 * Called on initialization.
	 * @return void
	 */
	void Start () 
	{
		
		//Initialized because this object moves through scenes
		_replayMode = GameObject.Find (REPLAY_MODE_NAME);
		
	}
	
	/*
	 * Called on collision(trigger).
	 * @param Collider
	 * @return void
	 */
	void OnTriggerEnter(Collider pCollider)
	{
		//if collide with the ball
		if (pCollider.gameObject.name.Equals(BALL_NAME))
		{
			if(_lastLevel != null)
			{
				ControllerScript[] tabMonoBehaviour = _lastLevel.GetComponentsInChildren<ControllerScript>();
				
				foreach (ControllerScript monoBehaviour in tabMonoBehaviour) 
				{ 
						_dataContainer.GetComponent<DataContainerScript>()._countActivatedStages--;
						monoBehaviour.enabled = false;
				}
				DestroyObject(_lastLevel);
			}
			//Destroys last stage (useless and free memory)
			
			if(!_replayMode.GetComponent<ReplayModeScript>()._replayMode)
			{
				//Get and enable children's script
				ControllerScript[] tabMonoBehaviour = this.GetComponentsInChildren<ControllerScript>();
				
				foreach (ControllerScript monoBehaviour in tabMonoBehaviour) 
				{ 
						_dataContainer.GetComponent<DataContainerScript>()._countActivatedStages++;
						monoBehaviour.enabled = true;
				}
			}
			//Desactivates trigger
			this.collider.enabled = false;
		}	
	}	
}
